import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wayofdressing/components/bigbutton.dart';
import 'package:model_viewer_plus/model_viewer_plus.dart';
import 'package:wayofdressing/contraints.dart';
import 'package:wayofdressing/screens/body_manage_screen.dart';
import 'package:wayofdressing/screens/match_screen.dart';
import 'package:wayofdressing/components/singlechildbutton.dart';
import 'package:wayofdressing/screens/aichat_screen.dart';
import 'package:wayofdressing/screens/closet_screen.dart';
import 'package:wayofdressing/screens/calender_screen.dart';
import 'package:wayofdressing/components/inmenubutton.dart';
import 'package:wayofdressing/weather.dart';

class HomeScreen extends StatefulWidget {
  static final String id = 'homescreen';

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  int threeDNumber = 1;
  WeatherService weatherService = WeatherService();
  Map<String,String> weather={};
  String city='';
  String weatherText='';

  @override
  void initState() {
    super.initState();
    _getWeather();
  }

  Future<void> _getWeather() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    DateTime now = DateTime.now();
    String currentDateString = '${now.year}-${now.month}-${now.day}';

    String cachedDateString = prefs.getString('cachedDate') ?? '';

    if (cachedDateString != currentDateString) {
      try {
        // Fetch new weather data
        Map<String, String>? fetchedWeather = await weatherService.getWeather();
        if (fetchedWeather != null) {
          weather = fetchedWeather;
          setState(() {
            city = weather['City'] ?? 'Unknown';
            weatherText = (weather['Weather'] ?? '') + (weather['Temperature'] ?? '');
          });

          // Update SharedPreferences with new data
          await prefs.setString('city', city);
          await prefs.setString('weather', weatherText);
          await prefs.setString('cachedDate', currentDateString);
        }
      } catch (e) {
        print('Error getting weather data: $e');
      }
    } else {
      // If cached date matches current date, use cached data
      city = prefs.getString('city') ?? '';
      weatherText = prefs.getString('weather') ?? '';
      setState(() {
        city = city;
        weatherText = weatherText;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffffaf0),
      appBar: AppBar(
        backgroundColor: Color(0xfffffaf0),
        elevation: 0,
        toolbarHeight: 80,
        leadingWidth: 200,
        leading: Row(
          children: [
            SizedBox(
              width: 20,
            ),
            MenuAnchor(
              menuChildren: [
                InMenuButton(
                  text: '待开发',
                  onPressed: (){
                    print(weather);
                  },
                ),
              ],
              style: MenuStyle(
                alignment: Alignment(-0.7, 1),
                shape: MaterialStateProperty.all(
                  RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(25),
                  ),
                ),
                padding: MaterialStateProperty.all(EdgeInsets.all(15.0)),
                shadowColor: MaterialStateProperty.all(Colors.transparent),
                backgroundColor: MaterialStateProperty.all(
                  Colors.black.withOpacity(0.4),
                ),
              ),
              builder: (BuildContext context, MenuController controller,
                  Widget? child) {
                return GestureDetector(
                  onTap: () {
                    if (controller.isOpen) {
                      controller.close();
                    } else {
                      controller.open();
                    }
                  },
                  child: Icon(
                    Icons.list_rounded,
                    size: kAppBarButtonSize,
                    color: Colors.black,
                  ),
                );
              },
            ),
            SizedBox(
              width: 10,
            ),
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  city,
                  style: TextStyle(
                    color: Colors.black,
                    fontWeight: FontWeight.bold,
                    fontSize: 12,
                  ),
                ),
                Text(
                  weatherText,
                  style: TextStyle(
                    color: Colors.black,
                    fontWeight: FontWeight.bold,
                    fontSize: 12,
                  ),
                ),
              ],
            )
          ],
        ),
        actions: [
          MenuAnchor(
            menuChildren: [
              InMenuButton(
                onPressed: () {},
                text: '待开发',
                alignment: Alignment.centerRight,
              ),
            ],
            style: MenuStyle(
              shape: MaterialStateProperty.all(
                RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0),
                ),
              ),
              alignment: Alignment(-3, 0.7),
              padding: MaterialStateProperty.all(EdgeInsets.all(15.0)),
              shadowColor: MaterialStateProperty.all(Colors.transparent),
              backgroundColor: MaterialStateProperty.all(
                Colors.black.withOpacity(0.4),
              ),
            ),
            builder: (BuildContext context, MenuController controller,
                Widget? child) {
              return GestureDetector(
                onTap: () {
                  if (controller.isOpen) {
                    controller.close();
                  } else {
                    controller.open();
                  }
                },
                child:Row(
                  children: [
                    CircleAvatar(
                      backgroundImage: AssetImage('images/peanut.jpg'),
                      radius: 22,
                      backgroundColor: Colors.black,
                    ),
                  ],
                ),
              );
            },
          ),
          SizedBox(
            width: 20,
          )
        ],
      ),
      body: Row(
        children: [
          SizedBox(
            width: 20,
          ),
          Expanded(
            child: Column(
              children: [
                Expanded(
                  flex: 25,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      singleChildButton(
                        onPressed: () {
                          Navigator.pushNamed(context, CalenderScreen.id);
                        },
                        childWidget: Icon(
                          Icons.calendar_month_rounded,
                          size: 80,
                        ),
                      ),
                      bigButton(
                        onPressed: () {
                          Navigator.pushNamed(context, AiChatScreen.id);
                        },
                        buttonIcon: Icon(
                          Icons.filter_vintage_outlined,
                          size: 50,
                          color: Colors.black,
                        ),
                        text: 'Peanut',
                        flexNumber: 2,
                      )
                    ],
                  ),
                ),
                Expanded(
                  flex: 80,
                  child: Container(
                    margin: EdgeInsets.all(10),
                    decoration: BoxDecoration(
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                            spreadRadius: 2, // 阴影扩展半径
                            blurRadius: 5, // 阴影模糊半径
                            offset: Offset(0, 8), // 阴影偏移量
                          ),
                        ],
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(25)),
                    child: Row(
                      children: [
                        Expanded(
                          flex: 10,
                          child: Container(
                            decoration: BoxDecoration(
                                color: Colors.transparent,
                                borderRadius: BorderRadius.circular(25)),
                            child: Stack(
                              children: <Widget>[
                                Opacity(
                                  opacity: threeDNumber == 1 ? 1 : 0,
                                  child: IgnorePointer(
                                    ignoring: threeDNumber == 1 ? false : true,
                                    child: ModelViewer(
                                      src: '3dmodels/jeo1.glb',
                                      autoRotate: true,
                                    ),
                                  ),
                                ),
                                Opacity(
                                  opacity: threeDNumber == 2 ? 1 : 0,
                                  child: IgnorePointer(
                                    ignoring: threeDNumber == 2 ? false : true,
                                    child: ModelViewer(
                                      src: '3dmodels/jeo2.glb',
                                      autoRotate: true,
                                    ),
                                  ),
                                ),
                                Opacity(
                                  opacity: threeDNumber == 3 ? 1 : 0,
                                  child: IgnorePointer(
                                    ignoring: threeDNumber == 3 ? false : true,
                                    child: ModelViewer(
                                      src: '3dmodels/jeo3.glb',
                                      autoRotate: true,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                        Expanded(
                            flex: 3,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                GestureDetector(
                                  onTap: () {
                                    setState(() {
                                      if (threeDNumber < 3)
                                        threeDNumber += 1;
                                      else
                                        threeDNumber = 1;
                                    });
                                  },
                                  child: Icon(
                                    Icons.play_arrow_rounded,
                                    color: Colors.black,
                                    size: 50,
                                  ),
                                ),
                                TextButton(
                                  onPressed: () {
                                    Navigator.pushNamed(context, BodyManageScreen.id);
                                  },
                                  style: ButtonStyle(
                                    padding: MaterialStateProperty.all(
                                        EdgeInsets.all(0)),
                                    minimumSize:
                                        MaterialStateProperty.all(Size(80, 40)),
                                    shape: MaterialStateProperty.all(
                                      RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(25),
                                      ),
                                    ),
                                  ),
                                  child: Text(
                                    '尺码管理',
                                    style: TextStyle(
                                      color: Colors.black,
                                      fontSize: 12,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                )
                              ],
                            ))
                      ],
                    ),
                  ),
                ),
                Expanded(
                  flex: 36,
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      bigButton(
                        onPressed: () {
                          Navigator.pushNamed(context, MatchScreen.id);
                        },
                        buttonIcon: Icon(
                          Icons.all_inclusive_rounded,
                          size: kBigButtonSize,
                        ),
                        text: '搭配',
                        flexNumber: 1,
                      ),
                      bigButton(
                        onPressed: () {
                          Navigator.pushNamed(context, ClosetScreen.id);
                        },
                        text: '衣橱',
                        buttonIcon: Icon(
                          Icons.checkroom_rounded,
                          size: kBigButtonSize,
                        ),
                        flexNumber: 1,
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
          SizedBox(
            width: 20,
          ),
        ],
      ),
    );
  }
}
